package com.andy.module.util

import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import java.util.regex.Pattern

/**
 * @creator:LuoFan
 * @date:2022/6/22
 * @description:通过检验正则表达式输入
 */

class PatternInputFilter(patternStr: String) : InputFilter {

    private val mPattern: Pattern=Pattern.compile(patternStr)

    /**
     * @param source 新输入的字符串
     * @param start  新输入的字符串起始下标，一般为0
     * @param end    新输入的字符串终点下标，一般为source长度-1
     * @param dest   输入之前文本框内容
     * @param dstart 原内容起始坐标，一般为0
     * @param dend   原内容终点坐标，一般为dest长度-1
     * @return 输入de内容
     */
    override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence {
        val sourceText = source.toString()
        val destText = dest.toString()
        //验证删除等按键
        if (TextUtils.isEmpty(sourceText)) {
            return ""
        }
        val content = destText + sourceText
        val matcher = mPattern.matcher(content)
        return if (!matcher.matches()) {
            ""
        } else source
    }


}